<script setup lang="ts">
import {ref, useTemplateRef, computed} from 'vue'
import {useHttpPagingResult} from "@/hooks/http";
import {editUserStatus, getUserListApi, updatedUserApi, createdUserApi, deletedUserDetailApi, recycleUserApi} from "@/apps/admin/api/user/user"
import {TableColumn} from "@/components/AppTable/TableType";
import UserDetails from "./components/UserDetails/index.vue"
import {usePopupForm} from "@/components/FunctionComponents";

const {getRequestData, list, pagination, loading} = useHttpPagingResult(function (qyery) {
  return getUserListApi({...qyery, ...where.value})
})

const where = ref<object>({
  is_recycle: 0,
  nickname: '',
  mobile: '',
  sex: '',
  level_id: '',
  tags_ids: '',
  status: '',
  created_at: []
})

/**
 *  表列配置
 */
const columns = computed<TableColumn[]>(() => {
  let column: TableColumn[] = [
    {prop: 'id', label: "ID", minWidth: 80, fixed: 'left'},
    {prop: 'nickname', label: "名称/昵称", minWidth: 120, showOverflowTooltip: true, fixed: 'left'},
    {prop: 'avatar', label: "头像", type: "image", width: 60, fixed: 'left'},
    {prop: 'mobile', label: "手机号", width: 115, fixed: 'left'},
    {type: 'action', fixed: 'left', width: where.value?.is_recycle === 0 ? 115 : 70, label: '操作', align: 'center'},
    {prop: '_sex', label: '性别', width: 80},
    {prop: '_tags', label: '标签', minWidth: 120, showOverflowTooltip: true, render: (row: any) => row._tags.join(' / ')},
    {prop: '_level', label: '等级', minWidth: 120},
    {prop: 'status', label: '状态', type: 'status', edit: where.value?.is_recycle === 0, width: 90, activeText: '已启用', inactiveText: '已禁用'},
    {prop: 'created_at', label: '注册时间', type: 'timestramp', width: 165},
    {prop: 'last_login', label: '上次登录', type: 'timestramp', width: 165},
  ]
  if (where.value.is_recycle) {
    column.push({
      prop: 'deleted_at', label: '删除时间', type: 'timestramp', width: 165
    })
  }
  return column
})


/**
 * 数据更改事件
 * @param event
 * @param value
 * @param rows
 * @param index
 */
async function userUpdate(event: string, value: number, rows: any, index: number) {
  if (event === 'status') {
    const {code} = await editUserStatus(rows.id, value)
    if (code === 200) {
      list.value[index].status = value
    }
  }
}

//详情组件
const detail = useTemplateRef('details')

/**
 * 打开详情
 * @param id
 */
function openDetail(id: number) {
  detail.value?.open(id)
}

/**
 * 编辑表单
 */
function updatedUserData(id: number) {
  usePopupForm({
    api: updatedUserApi,
    query: {id: id},
    width: '720px',
    onSuccess: getRequestData
  })
}


/**
 * 新建表单
 */
function createdUserData() {
  usePopupForm({
    api: createdUserApi,
    width: '720px',
    onSuccess: getRequestData
  })
}


/**
 * 删除会员
 */
function deletedUser(id: number) {
  deletedUserDetailApi(id).then((res) => {
    if (res.code === 200) {
      getRequestData()
    }
  })
}


/**
 * 恢复会员
 */
function recycleUser(id: number) {
  recycleUserApi(id).then((res) => {
    if (res.code === 200) {
      getRequestData()
    }
  })
}

</script>
<template>
  <div>
    <data-card>
      <search-form title="会员搜索" :disabled="loading" label-width="45px" @search="getRequestData({page:1,size:pagination.size})">
        <el-form-item label="会员名称" prop="nickname">
          <el-input v-model.trim="where.nickname" placeholder="请输入会员名"></el-input>
        </el-form-item>
        <template #more>
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model.trim="where.mobile" placeholder="请输入手机号"/>
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="性别" prop="sex">
                <app-select v-model="where.sex" api="/filter-panel/sex"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="会员等级" prop="level_id">
                <app-select v-model="where.level_id" api="/filter-panel/user-level"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="会员标签" prop="tags_ids">
                <app-select v-model="where.tags_ids" api="/filter-panel/user-tags"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="会员状态" prop="tags_ids">
                <app-select v-model="where.status" :option="[{label:'已禁用',value:0},{label:'已启用',value:1}]"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="注册时间" prop="created_at">
            <date-range v-model="where.created_at"></date-range>
          </el-form-item>
        </template>
      </search-form>
    </data-card>
    <app-interval></app-interval>
    <data-card title="用户管理">
      <template #left>
        {{ where.is_recycle ? '会员回收站' : '系统会员' }}
        <el-switch
            v-model="where.is_recycle"
            @change="getRequestData({page:1,size:pagination.size})"
            :active-value="1"
            :inactive-value="0"
            class="app-margin-left-tiny"
            inline-prompt
            active-text="回收站"
            inactive-text="回收站"
        />
      </template>
      <template #right>
        <el-button size="small" type="primary" @click="createdUserData">新建</el-button>
      </template>
      <app-interval></app-interval>
      <app-table drawer height="calc(var(--ach) - 225px)" :columns :data="list" :pagination :loading @reload="getRequestData" @update="userUpdate">
        <template #action="{row}">
          <operate-link v-if="where.is_recycle" @tap="recycleUser(row.id)">恢复</operate-link>
          <el-space v-else>
            <operate-link @tap="updatedUserData(row.id)">编辑</operate-link>
            <operate-link @tap="deletedUser(row.id)" confirm="确定要删除该会员吗?">删除</operate-link>
          </el-space>
        </template>
        <template #nickname="{row}">
          <span v-if="where.is_recycle">
             {{ row.nickname }}
          </span>
          <el-link v-else type="primary" @click="openDetail(row.id)">
            {{ row.nickname }}
          </el-link>
        </template>
      </app-table>
    </data-card>
    <user-details ref="details" @close="getRequestData"></user-details>
  </div>
</template>